package com.wl.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wl.basic.exception.BusinessException;
import com.wl.basic.jwt.JwtUtils;
import com.wl.basic.jwt.LoginData;
import com.wl.basic.jwt.RsaUtils;
import com.wl.basic.util.AjaxResult;
import com.wl.basic.util.HttpUtil;
import com.wl.basic.util.Md5Utils;
import com.wl.basic.util.StrUtils;
import com.wl.system.domain.Menu;
import com.wl.system.mapper.MenuMapper;
import com.wl.system.mapper.PermissionMapper;
import com.wl.user.constant.WxConstants;
import com.wl.user.domain.Logininfo;
import com.wl.user.domain.User;
import com.wl.user.domain.Wxuser;
import com.wl.user.dto.LoginDto;
import com.wl.user.mapper.LogininfoMapper;
import com.wl.user.mapper.UserMapper;
import com.wl.user.mapper.WxuserMapper;
import com.wl.user.service.ILogininfoService;
import com.wl.basic.service.impl.BaseServiceImpl;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private MenuMapper menuMapper;


    /**
     * 后台登录业务
     *
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        //查询
        Logininfo logininfo = logininfoMapper.accoutLogin(loginDto);
        //校验空值
        if (logininfo == null) {
            throw new BusinessException("用户名错误");
        } else {
            //加密加盐
            String s = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            //和数据库密码对比
            if (!s.equals(logininfo.getPassword())) {
                throw new BusinessException("密码错误");
            } else {
               /* //获取uuid
                String token = UUID.randomUUID().toString();
                //存到redis里面
                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                //把后端查询到的数据装到map里面
                Map<String, Object> map = new HashMap<>();
                map.put("token", token);
                logininfo.setSalt(null);
                logininfo.setPassword(null);
                map.put("logininfo", logininfo);*/
               Map<String,Object> map =  loginSuccessJwtHandler(logininfo);
                return map;
            }
        }
    }
    //使用jwt
    private Map loginSuccessJwtHandler(Logininfo logininfo) {
        try {
           //1创建map
            HashMap<String, Object> map = new HashMap<>();
            //2.获取四个参数
            map.put("logininfo",logininfo);
            //设置登录信息表的值
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            //3.获取登录对象的类型 ，判断是否等于0
            if (logininfo.getType() == 0){
                //当前登录人的所有信息
                List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
                //添加到集合zhong
                map.put("permissions",permissions);
                loginData.setPermissions(permissions);
                //获取当前登录人的所有二级菜单和父类菜单
                List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
                //添加到mapzhong
                map.put("menus",menus);
                loginData.setMenus(menus);

                //再将上面三个数据装到logindata  使用加密JWT加密
                PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
                String s = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);
                //添加到mapzhong
                map.put("token",s);
                return map;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    /**
     * 微信登录业务
     *
     * @param
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)//源码时代提供
                .replace("SECRET", WxConstants.SECRET)//源码时代提供
                .replace("CODE", code);//手机扫描后传过来的code
        String jsonStr = HttpUtil.httpGet(url);
        // 把json格式转化为一个json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        // 获取token
        String accessToken = jsonObject.getString("access_token");
        // 获取openId
        String openId = jsonObject.getString("openid");
        // 根据opdnid查询t_wxuser对象
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        // 1.如果有，就返回前端，直接登录
        if (wxuser != null && wxuser.getUserId() != null && userMapper.loadById(wxuser.getUserId()) != null) {
            User user = userMapper.loadById(wxuser.getUserId());
            Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
            //调用上面的jwt方法
            Map<String,Object> map =  loginSuccessJwtHandler(logininfo);

            return AjaxResult.me().setResultObj(map);
        } else {
            // 2.如果没有就要进行验证
            String param = "?accessToken=" + accessToken + "&openId=" + openId;
            return AjaxResult.me().setSuccess(false).setResultObj(param);
        }
    }

    /**
     * 微信绑定业务
     * @param
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> result) {
        //获取前端传递的值
        String phone = result.get("phone");//手机号码
        String verifyCode = result.get("verifyCode");//验证码
        String accessToken = result.get("accessToken");//
        String openId = result.get("openId");//wxid
        //空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        //校验验证码是否过期
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if (obj == null){
            throw new BusinessException("验证码过期");
        }
        //校验验证码是否正确
        if(!obj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("验证码错误!!!");
        }
        //三：通过ack和openid发送第三个请求
        //3.1动态替换参数
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        //发请求
        String jsonStr = HttpUtil.httpGet(url);
        //四：处理响应的数据：json字符串 - json对象 - 获取wxUser的信息
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //五：绑定用户：将WxUser对象【第三个请求中获取】 与 User对象【通过手机创建】进行绑定
        User user = userMapper.loadByPhone(phone);//查询数据库电话
        //判断用户是否存在
        if (user == null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            //添加信息到登录表
            logininfoMapper.save(logininfo);
            //动态更新id
            user.setLogininfoId(logininfo.getId());
            //添加到用户表
            userMapper.save(user);
        }
        //user一定会有。并且user_id也有
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        //获取logininfo对象
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        //调用上面的jwt方法
        Map<String,Object> map =  loginSuccessJwtHandler(logininfo);

        return new AjaxResult().setResultObj(map);
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机密码
        String randomPwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");

        wxuser.setAddress(country+province+city);
        return wxuser;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}










